<template>
  <div class="comp-attachment_list">
    <Row>
      <Col :span="6" v-for="(row,index) in listData" :key="index" v-show="uploadStatus[index]?!uploadStatus[index].hidden:true">
      <div class="attachment-item">
        <div class="file-box">
          <div class="file-icon center-container" @click="imageClick({row,index})" :class="{'file-img':isImg(row)}" :style="itemBg(row)">
            <i class="ivu-load-loop ivu-icon ivu-icon-load-c" v-if="!isImg(row) && (uploadStatus[index]?uploadStatus[index].uploading:false)"></i>
            <!--<img @click="imageClick(row)" :src="imgPath(row)" v-else-if="isImg(row)"/>-->
            <Icon :type="fileIcon(index)" v-else-if="!isImg(row)"></Icon>
          </div>
          <div class="file-name">
            <a :href="imgPath(row,index)" download>{{row.name}}<span class="badge badge-file" v-if="dataFormat(row)">{{dataFormat(row)}}</span></a>
          </div>
        </div>
        <span @click="hideRow(index)">
            <Icon v-if="hasDelete" class="delete" type="close-circled"></Icon>
          </span>
      </div>
      </Col>
      <Col :span="6" v-if="hasUpload">
      <form ref="form" enctype="multipart/form-data" method="post">
        <div class="attachment-item attachment-upload">
          <Upload size="small"  :multiple="true" @fileUpload="uploadFile" :noAction="true"></Upload>
          <!--name="attachments"-->
        </div>
      </form>
      </Col>
    </Row>
    <ImageViewer :src="showImg" v-model="imgViewerShow"></ImageViewer>
  </div>
</template>

<script>
import moduleStore from "./store";
import $ from "@/common";
import baseGrid from "@/components/localGridPanel/index";
import Upload from "@/element/upload";
import ImageViewer from "@/element/imageViewer";
var imgFormatSet = new Set(["jpg", "jpeg", "png", "bmp", "jepg", "tiff"]);
var docFormatSet = new Set([
  "txt",
  "text",
  "doc",
  "docx",
  "pdf",
  "xlsx",
  "xls",
  "html",
  "xml",
  "json"
]);
export default {
  moduleStore,
  mixins: [baseGrid],
  data() {
    return {
      uploadPath: "service/{app}/{module}/attachment/upload",
      pathDownload:
        "/service/{app}/{module}/attachment/download/path?path={path}",
      isSlave: true,
      imgViewerShow: false,
      showImg: null,
      uploadStatus: []
    };
  },
  props: {},
  watch: {
    data: {
      handler() {
        for (let i in this.data) {
          i;
          this.uploadStatus.push({});
        }
        this.setData($.copyJson(this.data));
      }
    }
  },
  computed: {
    uploadParam() {
      var res = {};
      if (this.model && this.model.actions) {
        for (let i in this.model.actions) {
          let action = this.model.actions[i];
          if (action.code === "upload" && action.param) {
            res = $.setObj(action.param, res);
          }
        }
      }
      return res;
    },
    hasDelete() {
      return !this.viewMode;
    },
    hasUpload() {
      return !this.viewMode;
    }
  },
  created() {},
  methods: {
    formatMessage() {
      this.$Modal.warning({
        title: "文件格式错误",
        content:
          "请上传正确的文件</br>图片格式（jpg、png、gif、bmp、jpeg、tiff等）</br>文档格式（word、excel、pdf、txt、rft等）"
      });
    },
    uploadFile(files) {
      if (files && files.length) {
        let beginIndex = this.listData.length;
        for (let i = 0; i < files.length; i++) {
          let f = $.fileFormat(files[i].name);
          if (!imgFormatSet.has(f) && !docFormatSet.has(f)) {
            this.formatMessage();
            return;
          }
        }
        for (let i = 0; i < files.length; i++) {
          this.addRow({
            name: files[i].name
          });
          this.$set(this.uploadStatus, this.listData.length, {
            uploading: true,
            add: true
          });
        }
        $.upload(this.uploadPath, null, {
          param: this.uploadParam,
          form: this.$refs.form,
          files,
          fileCode: "attachments"
        })
          .then(res => {
            for (let i = 0; i < files.length; i++) {
              this.editRow({
                index: beginIndex + i,
                data: {
                  ...(this.defaultData || {}),
                  ...res.data[i]
                }
              });
              this.$set(this.uploadStatus, beginIndex + i, {
                uploading: false
              });
            }
          })
          .catch(() => {
            for (let i = 0; i < files.length; i++) {
              this.$set(this.uploadStatus, beginIndex + i, {
                uploading: false,
                error: true
              });
            }
          });
      }
    },
    //生成下载路径
    downloadPath(row, index) {
      var status = this.uploadStatus[index];
      if (status && status.add) {
        return null;
      } else {
        return $.composePath(this.pathDownload, {
          ...row,
          ...this.uploadParam
        });
      }
    },
    itemBg(row) {
      var style = {};
      if (this.isImg(row) && this.imgPath(row)) {
        style["background-image"] = `url(${this.imgPath(row)})`;
      }
      return style;
    },
    //删除才用暂时隐藏数据的方法，而非直接删除数据，不会在新文件上传时因为删除数据导致index错位
    hideRow(index) {
      this.$set(this.uploadStatus[index], "hidden", true);
    },
    dataFormat(data) {
      if (data.path) {
        var pathArr = data.path.split("/");
        var code = pathArr[pathArr.length - 1].match(/\.(.*?)$/);
        if (code && code[1]) {
          return code[1];
        }
      }
      return false;
    },
    isImg(data) {
      if (!data.path) {
        return false;
      } else {
        return data.path.match(/.(png|gif|jpeg|jpg|bmp)$/);
      }
    },
    imgPath(row, index) {
      var path = row.path;
      if (path) {
        if (path[0] !== "/") {
          path = "/" + path;
        }
        if (!path.match(/^\/group/)) {
          path = this.downloadPath(row, index);
        }
      }
      return path;
    },
    imageClick({ row, index }) {
      if (!this.isImg(row, index)) return;
      this.imgViewerShow = true;
      this.showImg = this.imgPath(row, index);
    },
    fileIcon(index) {
      if (!this.uploadStatus[index]) {
        this.$set(this.uploadStatus, index, {});
      }
      var status = this.uploadStatus[index];
      if (status.error) {
        //上传错误
        return "alert-circled";
      }
      //普通状态文件
      return "document-text";
    },
    getData() {
      var list = [];
      this.listData.forEach((data, index) => {
        if (this.uploadStatus[index]) {
          if (
            !this.uploadStatus[index].hidden &&
            !this.uploadStatus[index].uploading &&
            !this.uploadStatus[index].error
          ) {
            list.push(data);
          }
        } else {
          list.push(data);
        }
      });
      return list;
    }
  },
  components: {
    Upload,
    ImageViewer
  }
};
</script>

<style lang="less">
.comp-attachment_list {
  margin: 0 -8px;
  .file-img {
    background-position: center;
    background-size: contain;
    background-repeat: no-repeat;
    cursor: pointer;
  }
  .attachment-item {
    text-align: center;
    height: 160px;
    position: relative;
    margin: 8px 8px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border-radius: 4px;
    background: #f7f7f7;
    border: 2px solid transparent;
    &:hover {
      border: 2px solid #b0d7ff;
    }
    &.attachment-upload {
      display: block;
      border: none;
    }
    .badge-file {
      padding: 1px 8px;
      display: inline-block;
      background: #69cdff;
      font-weight: bold;
      color: #fff;
      border-radius: 4px;
      margin-left: 8px;
    }
    .file-box {
      height: 100%;
      display: flex;
      width: 100%;
      overflow: hidden;
      flex-direction: column;
      padding: 8px;
      .file-icon {
        font-size: 36px;
        width: 100%;
        text-align: center;
        left: 0;
        right: 0;
        flex: 1;
        color: #2c9fff;
        > img {
          width: 100%;
          height: 100%;
          padding: 0 10px;
          cursor: pointer;
        }
        .ivu-icon-alert-circled {
          color: #ffc650;
        }
        .ivu-load-loop {
          font-size: 24px;
        }
      }
      .file-name {
        padding: 8px;
        word-break: break-all;
        line-height: 1.2;
      }
    }
    .delete {
      font-size: 24px;
      position: absolute;
      top: -12px;
      right: -12px;
      background: #fff;
      color: #f56262;
      &:hover {
        color: #ff8282;
      }
      cursor: pointer;
    }
  }
}
</style>
